package com.kmt.plaza.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.kmt.plaza.vo.ResStatus;
import com.kmt.plaza.vo.ResultVO;
import io.jsonwebtoken.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.util.concurrent.TimeUnit;

@Component//标注Spring管理的Bean，使用@Component注解在一个类上，表示将此类标记为Spring容器中的一个Bean
public class CheckTokenInterceptor implements HandlerInterceptor {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取前端请求的方式
        String method = request.getMethod();
        //判断请求方式是否为OPTIONS
        if("OPTIONS".equalsIgnoreCase(method)){
            return true;
        }
        //因为浏览器的预检机制，第一次请求是试探性的不会携带token，如果第一次请求正常，浏览器才会携带token进行第二次请求。
        //获取token
        String token = request.getHeader("token");
        System.out.println("----"+token);
        if(token==null){
            ResultVO resultVO = new ResultVO(ResStatus.LOGIN_FAIL, "请先登录", null);
            //提示请先登录
            doResponse(response,resultVO);
        }else{
            //有token就去redis找
            String s = stringRedisTemplate.boundValueOps(token).get();
            if(s == null){
                //从未登录或登录过期
                ResultVO resultVO = new ResultVO(ResStatus.LOGIN_FAIL, "请先登录", null);
                //提示请先登录
                doResponse(response,resultVO);
            }else{
                //s不为空
                stringRedisTemplate.boundValueOps(token).expire(30, TimeUnit.MINUTES);
                return true;
            }
        }

        //false拦截、true放行
        return false;
    }
    private void doResponse(HttpServletResponse response,ResultVO resultVO)throws IOException {
        response.setContentType("application/json");
        response.setCharacterEncoding("utf-8");
        PrintWriter out = response.getWriter();
        String s = new ObjectMapper().writeValueAsString(resultVO);
        out.print(s);
        out.flush();
        out.close();
    }
}
